import { BASE_URL } from '../../common/config';
// 获取应用实例
const app = getApp()
Page({
  data: {
    code:'',
    token:'',
    openid:'',
    checked: false,
    userInfo:{}
  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
   // 调用 wx.login 获取 code
   getCode() {
    // return new Promise((resolve) => {
      if(!this.data.checked){
        wx.showToast({
          title: '请勾选同意',
          icon:'none'
        })
        return
      }
      wx.getUserProfile({
        desc: '用于完善个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          this.setData({
            userInfo: res.userInfo
          })
          wx.login({
            success: ({ code }) => {
              console.log("获取到的 code:", code);
              this.setData({
                code: code
              });
              wx.showLoading({
                title: '正在登录...',
                mask: true // 遮罩层，防止用户点击其它地方
              });
              wx.request({
                url: `${BASE_URL}/GetOpenid`,
                method:'POST',
                data:{
                  code:code,
                  wxname:this.data.userInfo.nickName,
                  url:this.data.userInfo.avatarUrl
                },
                // header: {
                //   'content-type': 'application/x-www-form-urlencoded'
                // },
                success:(res)=>{
                  wx.hideLoading();
                  console.log("获取openid成功：",res)
                  // let token=res.data.data.token
                  let openid=res.data.data.openid
                  // let openid='oi5-p6weibesKAhO8v4PzvetusRg'
                  // let openid='oi5-p65AVk9p_Dlxt1tvc9ZL7x2I'
                  // let openid='oi5-p6_PdipfOJGEL0IDlu50yKbI'
                  // wx.setStorageSync('token', token);
                  wx.setStorageSync('openid', openid);
                  // console.log('从缓存中拿到的token：',wx.getStorageSync('token'))
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                },
                fail:(err)=>{
                  console.log("请求失败",err)
                }
              })
              // resolve(code);
            },
          });
        }
      })
  },
  // 调用后端接口，传递 code 获取 sessionKey
  jump(e){
    let name=e.currentTarget.dataset.name
    console.log(name)
    wx.navigateTo({
      url: '/pages/agreement/agreement?name='+name,
    })
  }
})
